package com.keep.live.command.controller;

import cn.hutool.core.util.RuntimeUtil;
import com.keep.live.command.schedule.TeminateTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping("/command")
@Slf4j
public class CommandController {


    @Autowired
    private TeminateTask TeminateTask;

    private static ConcurrentHashMap<String, String> pidMap = new ConcurrentHashMap<>();

    /**
     * @return
     */
    @PostMapping(value = "/start")
    public String start(@RequestBody List<String> args) {
        String[] commands = args.toArray(new String[0]);
        log.info("commands {}", Arrays.toString(commands));
        List<String> res = RuntimeUtil.execForLines(commands);
        if (!CollectionUtils.isEmpty(res)) {
            String newPid = res.get(0);
            pidMap.put(Arrays.toString(commands), newPid);
        }

        return res.toString();

    }

    @PostMapping(value = "/stop")
    public String stop(@RequestBody List<String> args) {

        String[] commands = args.toArray(new String[0]);
        log.info("commands {}", Arrays.toString(commands));
        String pid = pidMap.get(Arrays.toString(commands));
        log.info("pid {}", pid);
        return TeminateTask.stop(pid);

    }


}
